﻿using BaoJiPlayer.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BaoJiPlayer
{
    public partial class Main : Form
    {
        private int TopPlayHour { get; set; }

        private int TopSleepHour { get; set; }

        public Main()
        {
            InitializeComponent();
        }

        private void btnAddNewAge_Click(object sender, EventArgs e)
        {
            try
            {
                List<PlayList> dList = this.doSelectFiles();
                xmlHelper.WriteXml("PlayList.xml", "NewAge", dList);

                this.Text = "煲机 - 轻音乐添加成功";
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：添加轻音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnAddPopMsc_Click(object sender, EventArgs e)
        {
            try
            {
                List<PlayList> dList = this.doSelectFiles();
                xmlHelper.WriteXml("PlayList.xml", "PopMsc", dList);
                this.Text = "煲机 - 流行音乐添加成功";
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：添加流行音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private List<PlayList> doSelectFiles()
        {
            List<PlayList> dList = new List<PlayList>();

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择音乐文件";      //打开对话框的标题
            ofd.Multiselect = true; //设置多选
            ofd.Filter = @"音乐文件|*.mp3||*.wav";    //设置文件格式筛选
            ofd.ShowDialog();   //显示打开对话框
            string[] aryFiles = ofd.FileNames;       //获得在文件夹中选择的所有文件的全路径
            for (int i = 0; i < aryFiles.Length; i++)
            {
                string Name = Path.GetFileName(aryFiles[i]);
                string File = aryFiles[i];

                PlayList add = new PlayList();
                add.Name = Name;
                add.File = File;
                dList.Add(add);
            }
            return dList;
        }

        private void btnLoadNewAge_Click(object sender, EventArgs e)
        {
            try
            {
                
                List<PlayList> dList = xmlHelper.ReadXml("PlayList.xml", "NewAge");
                if (dList.Count == 0)
                {
                    this.Text = "煲机 - 轻音乐无数据";
                    return;
                }

                this.listPlaying.Items.Clear();

                int No = 0;
                foreach(PlayList data in dList)
                {
                    No += 1;

                    this.listPlaying.Items.Add(new ListItem(No + ". " + data.Name, data.File));
                }
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：加载轻音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnClrPopMsc_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = MessageBox.Show("确定要清除数据吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

                if (dr == DialogResult.OK)
                {
                    xmlHelper.ClearMscType("PlayList.xml", "PopMsc");
                    this.Text = "煲机 - 流行音乐添加成功";
                }
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：清除流行音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private int CurMinis = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if(SysVar.PlayingHours >= this.TopPlayHour)
                {//到达连续播放5小时
                    
                    if (SysVar.SleepHours == 0)
                    {
                        this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：5小时连播到时.", DateTime.Now.ToString()),""));
                        this.wmPlayer.Ctlcontrols.pause();
                        this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：播放暂停,进入睡眠模式.", DateTime.Now.ToString()),""));
                    }
                    SysVar.SleepHours += 1;
                }
                else
                {
                    SysVar.PlayingHours += 1;
                    CurMinis += 1;

                    if(CurMinis >= 3600)
                    {
                        CurMinis = 0;
                        int TotPlayHours = xmlHelper.SetHour("PlayList.xml", 1);
                        this.lbPlayingHours.Text = TotPlayHours + "H";
                        this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：累计播放时长{1}小时.", DateTime.Now.ToString(), TotPlayHours.ToString()),""));
                    }
                }

                if(SysVar.SleepHours >= this.TopSleepHour)
                {//睡眠已过,继续播放
                    SysVar.SleepHours = 0;
                    SysVar.PlayingHours = 0;
                    this.wmPlayer.Ctlcontrols.play();
                    this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：睡眠唤醒,进入播放模式.", DateTime.Now.ToString()),""));
                }
            }
            catch(Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：计时器异常〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if(this.btnStart.Text == "继续")
                {
                    this.btnStart.Text = "开始";
                    this.btnStart.Enabled = false;
                    this.btnPause.Enabled = true;
                    this.timer1.Enabled = true;
                    this.wmPlayer.Ctlcontrols.play();
                }
                else
                {
                    this.btnPause.Enabled = true;
                    this.btnStop.Enabled = true;
                    this.timer1.Enabled = true;

                    this.listTimeLine.Items.Clear();
                    this.btnStart.Enabled = false;

                    this.TopPlayHour = int.Parse(this.numPlayHour.Text) * 60 * 60;
                    this.TopSleepHour = int.Parse(this.numSleepHour.Text) * 60 * 60;

                    this.listPlaying.SelectedIndex = 0;
                    string FilePath = ((ListItem)this.listPlaying.SelectedItem).Value;
                    this.wmPlayer.URL = FilePath;

                    SysVar.PlayingHours = 0;
                    SysVar.SleepHours = 0;
                    CurMinis = 0;
                    this.timer1.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                this.btnStart.Enabled = true;
                this.btnStop.Enabled = true;
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：开始〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if(this.btnStart.Enabled == false || this.btnStart.Text == "继续")
                {
                    DialogResult dr = MessageBox.Show("正在煲机中,确定要停止吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

                    if (dr == DialogResult.OK)
                    {
                        this.btnStart.Enabled = true;
                        this.btnStop.Enabled = false;
                        this.btnPause.Enabled = false;
                        this.btnStart.Text = "开始";
                        SysVar.PlayingHours = 0;
                        SysVar.SleepHours = 0;
                        CurMinis = 0;
                        this.timer1.Enabled = false;
                        this.wmPlayer.Ctlcontrols.stop();
                    }
                }
            }
            catch (Exception ex)
            {
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = true;
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：停止〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }
        private void Main_Load(object sender, EventArgs e)
        {
            try
            {
                this.wmPlayer.settings.volume = 100;
                P_PlayList ppl = xmlHelper.Get_PlayListAttr("PlayList.xml");
                this.lbPlayingHours.Text = ppl.TotHour + "H";
                this.numSleepHour.Value = ppl.SleepHour;
                this.numPlayHour.Value = ppl.PlayHour;

                this.listPlaying.Items.Clear();
                List<PlayList> NewAgeList = xmlHelper.ReadXml("PlayList.xml", "NewAge");
                List<PlayList> PopMscList = xmlHelper.ReadXml("PlayList.xml", "PopMsc");

                int No = 0;
                foreach (PlayList data in NewAgeList)
                {
                    No += 1;
                    this.listPlaying.Items.Add(new ListItem(No + ". " + data.Name, data.File));
                }
                foreach (PlayList data in PopMscList)
                {
                    No += 1;
                    this.listPlaying.Items.Add(new ListItem(No + ". " + data.Name, data.File));
                }
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：初始化主程序〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnClrNewAge_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = MessageBox.Show("确定要清除数据吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

                if(dr == DialogResult.OK)
                {
                    xmlHelper.ClearMscType("PlayList.xml", "NewAge");
                    this.Text = "煲机 - 轻音乐清除成功";
                }

            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：清除轻音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnLoadPopMsc_Click(object sender, EventArgs e)
        {
            try
            {
                
                List<PlayList> dList = xmlHelper.ReadXml("PlayList.xml", "PopMsc");
                if (dList.Count == 0)
                {
                    this.Text = "煲机 - 流行音乐无数据";
                    return;
                }

                this.listPlaying.Items.Clear();

                int No = 0;
                foreach (PlayList data in dList)
                {
                    No += 1;
                    this.listPlaying.Items.Add(new ListItem(No + ". " + data.Name, data.File));
                }
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：加载流行音乐〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void wmPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            try
            {
                if (this.wmPlayer.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
                {//播放完毕
                    int curIndex = this.listPlaying.SelectedIndex;
                    int nxtIndex = curIndex + 1;

                    if (nxtIndex >= this.listPlaying.Items.Count)
                    {
                        nxtIndex = 0;
                    }
                    this.listPlaying.SelectedIndex = nxtIndex;

                    string FilePath = ((ListItem)this.listPlaying.SelectedItem).Value;
                    this.wmPlayer.URL = FilePath;
                }
                if (this.wmPlayer.playState == WMPLib.WMPPlayState.wmppsReady)
                {
                    try
                    {
                        this.wmPlayer.Ctlcontrols.play();
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：播放状态切换异常〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void Exit_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(this.btnStart.Enabled == false)
            {
                this.Text = "正在煲机中,不能退出";
                return;
            }
            this.notifyIcon1.Dispose();
            System.Environment.Exit(0);
        }

        private void MainPage_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.Show();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {//用户关闭
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                //系统关闭
            }
        }
        private About About;
        private void About_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SysVar.IsExistAbout)
            {
                this.About.Activate();
                return;
            }

            SysVar.IsExistAbout = true;

            this.About = new About();
            this.About.Show();
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.Show();
        }

        private void listPlaying_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (this.btnStart.Enabled == false)
                {
                    this.Text = "煲机 - 正在煲机中";
                    return;
                }
                string FilePath = ((ListItem)this.listPlaying.SelectedItem).Value;
                this.wmPlayer.URL = FilePath;
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：双击播放〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            this.btnStart.Text = "继续";
            this.btnStart.Enabled = true;
            this.btnPause.Enabled = false;

            try
            {
                this.wmPlayer.Ctlcontrols.pause();
                this.timer1.Enabled = false;
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：手工暂停.", DateTime.Now.ToString()), ""));
            }
            catch (Exception ex)
            {
                this.listTimeLine.Items.Add(new ListItem(String.Format("{0}：暂停〉{1}", DateTime.Now.ToString(), ex.Message), ""));
            }
        }

        private void numSleepHour_DoubleClick(object sender, EventArgs e)
        {
            this.numSleepHour.Enabled = true;
        }

        private void numSleepHour_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                this.numSleepHour.Enabled = false;
                int hour = (int)this.numSleepHour.Value;
                xmlHelper.SetSleepHour("PlayList.xml", hour);
            }
        }

        private void numSleepHour_Leave(object sender, EventArgs e)
        {
            this.numSleepHour.Enabled = false;
            int hour = (int)this.numSleepHour.Value;
            xmlHelper.SetSleepHour("PlayList.xml", hour);
        }

        private void numPlayHour_Leave(object sender, EventArgs e)
        {
            this.numPlayHour.Enabled = false;
            int hour = (int)this.numPlayHour.Value;
            xmlHelper.SetPlayHour("PlayList.xml", hour);
        }

        private void numPlayHour_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.numPlayHour.Enabled = false;
                int hour = (int)this.numPlayHour.Value;
                xmlHelper.SetPlayHour("PlayList.xml", hour);
            }
        }

        private void numPlayHour_DoubleClick(object sender, EventArgs e)
        {
            this.numPlayHour.Enabled = true;
        }

        private void label1_DoubleClick(object sender, EventArgs e)
        {
            this.numSleepHour.Enabled = true;
        }

        private void label2_DoubleClick(object sender, EventArgs e)
        {
            this.numPlayHour.Enabled = true;

        }
    }
}
/*
 windows media player控件的常用属性和方法

以下 music player 均为windows media player控件的名字。 
1.属性 
 1）musicPlayer.settings.autoStart：打开播放器时是否自动播放 。true：自动播放，false：不自动播放，默认自动播放。 
 2）musicPlayer.URL：要播放歌曲的路径。 
 3）musicPlayer.settings.mute：是否静音。true：静音，false：不静音。 
 4）musicPlayer.settings.volume：音量值大小，范围是1~100。 
 5）musicPlayer.Ctlcontrols.currentPositionString：当前播放时间。返回值是字符串类型，例如：02：23。 
 6）musicPlayer.Ctlcontrols.currentPosition：也是返回当前播放的时间。返回值是 double 类型，例如：133.8。 
 7）musicPlayer.currentMedia.name：返回当前播放歌曲的名字。 
 8）musicPlayer.playState：播放器当前的状态。 
  有一个枚举 WMPLib.WMPPlayState 说明了它的取值： 
  0——wmppsUndefined：未知状态 
  1——wmppsStopped：播放停止 
  2——wmppsPaused：播放暂停 
  3——wmppsPlaying：正在播放 
  4——wmppsScanForward：向前搜索 
  5——wmppsScanReverse：向后搜索 
  6——wmppsBuffering ：正在缓冲 
  7——wmppsWaiting：正在等待流开始 
  8——wmppsMediaEnded：播放流已结束 
  9——wmppsTransitioning ：准备新的媒体文件 
  10——wmppsReady：播放准备就绪 
  11——wmppsReconnecting：尝试重新连接流媒体数据 
  12——wmppsLast：上一次状态,状态没有改变

2.方法 
 1）musicPlayer.Ctlcontrols.play()：播放 
 2）musicPlayer.Ctlcontrols.pause()：暂停 
 3）musicPlayer.Ctlcontrols.stop()：停止
 */